package thread3;


class Resource {
    private volatile int number = 0;

    public void increment() {
        synchronized (OriginThreadDemo.class) {
            while (number == 0) {
                number++;
                System.out.println(Thread.currentThread().getName() + "\t" + number);
            }
        }
    }

    public void decrement() {
        synchronized (OriginThreadDemo.class) {
            while (number != 0) {
                number--;
                System.out.println(Thread.currentThread().getName() + "\t" + number);
            }
        }
    }
}

/**
 * 对同一个数字，两个线程，分别+1，-1，交替执行5次
 */
public class OriginThreadDemo {
    public static void main(String[] args) {
        Resource resource = new Resource();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                resource.increment();
            }
        }, "a").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                resource.decrement();
            }
        }, "b").start();
    }
}
